package com.gientech.spring.service;

import com.gientech.spring.mapper.CoffeeMapper;
import com.gientech.spring.model.Coffee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Slf4j
@Service
public class CoffeeService {

    private static final String CACHE_ALL_COFFEE = "springbucks-coffee";

    private static final String CACHE_ID_COFFEE = "springbucks-ID";

    @Autowired
    private CoffeeMapper coffeeMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public int saveCoffee(Coffee coffee) {
       return coffeeMapper.save(coffee);
    }

    public Coffee findById(Long id) {
        HashOperations<String, Long, Coffee> hashOperations = redisTemplate.opsForHash();
        if (redisTemplate.hasKey(CACHE_ID_COFFEE) && hashOperations.hasKey(CACHE_ID_COFFEE, id)) {
            log.info("Get coffee {} from Redis.", id);
            return hashOperations.get(CACHE_ID_COFFEE, id);
        }
        Coffee coffee = coffeeMapper.findById(id);
        if(null != coffee) {
            hashOperations.put(CACHE_ID_COFFEE, id, coffee);
            log.info("Coffee put to redis : {}", coffee);
        }
        log.info("Coffee Found: {}", coffee);
        return coffee;
    }

    public List<Coffee> findAll() {
        ListOperations<String, Coffee> listOperations = redisTemplate.opsForList();
        if (redisTemplate.hasKey(CACHE_ALL_COFFEE)) {
            log.info("Get coffee list {} from Redis.", CACHE_ALL_COFFEE);
            return (List<Coffee>) redisTemplate.boundListOps(CACHE_ALL_COFFEE);
        }
        List<Coffee> coffeeList = coffeeMapper.findAll();
        if(null != coffeeList) {
            listOperations.leftPushAll(CACHE_ALL_COFFEE, coffeeList);
            redisTemplate.expire(CACHE_ALL_COFFEE,1, TimeUnit.MINUTES);
            log.info("put coffee list {} to Redis.", CACHE_ALL_COFFEE);
        }
        return coffeeList;
    }

    public int update(Coffee coffee) {
        return coffeeMapper.updateById(coffee);
    }
}
